package com.cloud.wms.ui.in.fragment;

import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.cloud.core.eventBus.Event;
import com.cloud.core.utils.NumberUtils;
import com.cloud.core.utils.TimeUtils;
import com.cloud.widget.EditTextDel;
import com.cloud.widget.ScanText;
import com.cloud.widget.expand.ExpandLayout;
import com.cloud.wms.R;
import com.cloud.wms.base.BaseViewPagerFragment;
import com.cloud.wms.config.EventConfig;
import com.cloud.wms.ui.in.contract.InShelfContract;
import com.cloud.wms.ui.in.entity.InCommodityEntity;
import com.cloud.wms.ui.in.entity.InOrderEntity;
import com.cloud.wms.ui.in.entity.ShelfBatchEntity;
import com.cloud.wms.ui.in.presnter.InShelfPresenter;
import com.cloud.wms.ui.in.shelf.SelectBatchActivity;
import com.cloud.wms.ui.main.entity.TaskEntity;
import com.cloud.wms.widget.dialog.TaskCompleteDialog;
import com.trello.rxlifecycle3.LifecycleTransformer;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @Author:Chen
 * @Date: 2021-01-24 16:59
 * @Description: 批量上架
 */
public class ShelfBatchFragment extends BaseViewPagerFragment<InShelfPresenter> implements InShelfContract.View {
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.scan_text)
    ScanText scanText;
    @BindView(R.id.btn_good)
    CheckedTextView btnGood;
    @BindView(R.id.btn_bad)
    CheckedTextView btnBad;
    @BindView(R.id.tv_member_name)
    TextView tvMemberName;
    @BindView(R.id.tv_commodity_code)
    TextView tvCommodityCode;
    @BindView(R.id.tv_commodity_name)
    TextView tvCommodityName;
    @BindView(R.id.et_commodity_amount)
    EditText etCommodityAmount;
    @BindView(R.id.btn_next)
    TextView btnNext;
    @BindView(R.id.tv_order_commodity_amount)
    TextView tvOrderCommodityAmount;
    @BindView(R.id.tv_commodity_shelf_amount)
    TextView tvCommodityShelfAmount;
    @BindView(R.id.tv_recommend_pos)
    TextView tvRecommendPos;
    @BindView(R.id.et_shelf_pos)
    EditTextDel etShelfPos;
    @BindView(R.id.iv_toggle_batch)
    ImageView ivToggleBatch;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.expand_layout)
    ExpandLayout expandLayout;
    @BindView(R.id.nestedScrollView)
    NestedScrollView nestedScrollView;
    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            verifyRequired();
        }
    };
    private InOrderEntity inOrder;
    private InCommodityEntity commodityEntity;
    private ArrayList<ShelfBatchEntity> batchList = new ArrayList<>();
    private BaseQuickAdapter<ShelfBatchEntity, BaseViewHolder> mAdapter;
    private ArrayList<InCommodityEntity> inCommodityList = new ArrayList<>();
    private TaskEntity taskEntity;
    private String beginTime;
    private boolean isAdded;

    @Override
    protected int getResId() {
        return R.layout.fragment_in_shelf_batch;
    }

    @Override
    protected void setupComponent() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected void initEvent(Bundle bundle) {
        beginTime = TimeUtils.getCurrentDateAndTime();
        inOrder = getArguments().getParcelable("InOrder");
        taskEntity = getArguments().getParcelable("Task");
        if (inOrder != null)
            tvMemberName.setText(inOrder.getMemberName());
        else
            tvMemberName.setText(taskEntity.getMemberName());
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        rvList.setLayoutManager(manager);
        mAdapter = new BaseQuickAdapter<ShelfBatchEntity, BaseViewHolder>(R.layout.item_in_shelf_select_batch) {
            @Override
            protected void convert(BaseViewHolder helper, ShelfBatchEntity item) {
                helper.setText(R.id.tv_produce_date, item.getProductionDate())
                        .setText(R.id.tv_deadline_date, item.getExpirationDate())
                        .setText(R.id.tv_in_date, item.getInDate());
            }
        };
        rvList.setItemAnimator(new DefaultItemAnimator());
        rvList.setAdapter(mAdapter);

        mAdapter.setNewInstance(batchList);

        etShelfPos.setOnKeyListener(onKeyListenerImp);
        btnSubmit.setEnabled(false);
        btnNext.setEnabled(false);
        btnGood.setChecked(true);
        etShelfPos.addTextChangedListener(textWatcher);
        etCommodityAmount.addTextChangedListener(textWatcher);

        expandLayout.setOnExpansionUpdateListener((expansionFraction, state) -> {
            ivToggleBatch.setRotation(expansionFraction * 90);
        });
    }

    @Override
    public ScanText getScanText() {
        return scanText;
    }

    @Override
    protected void onScanHandle(String result, int resultCode) {
        super.onScanHandle(result, resultCode);
        if (etShelfPos.isFocused()) {
            etShelfPos.setText(result);
            etShelfPos.setSelection(result.length());
        } else {
            isAdded = false;
            scanText.addHistory(result);
            int commodityType = 1;
            resetView(false);
            if (btnBad.isChecked()) commodityType = 2;
            mPresenter.checkCommodityCode(inOrder != null ? String.valueOf(inOrder.getInID()) :  taskEntity.getMainBillID() + "", result, commodityType);
        }
    }

    @Override
    protected void initData() {

    }

    private void verifyRequired() {
        if (commodityEntity == null) {
            btnSubmit.setEnabled(false);
            btnNext.setEnabled(false);
            return;
        }
        if (batchList.isEmpty()) {
            btnSubmit.setEnabled(false);
            btnNext.setEnabled(false);
            return;
        }
        String shelfPos = etShelfPos.getText().toString().trim();
        if (TextUtils.isEmpty(shelfPos)) {
            btnSubmit.setEnabled(false);
            btnNext.setEnabled(false);
            return;
        }
        String commodityAmount = etCommodityAmount.getText().toString().trim();
        if (TextUtils.isEmpty(commodityAmount)) {
            btnSubmit.setEnabled(false);
            btnNext.setEnabled(false);
            return;
        }
        btnSubmit.setEnabled(true);
        btnNext.setEnabled(true);
    }

    private boolean verifySubmit() {
        if (commodityEntity == null) {
            info("请先扫描商品");
            return false;
        }
        String shelfPos = etShelfPos.getText().toString().trim();
        if (TextUtils.isEmpty(shelfPos)) {
            info("请扫描商品上架库位");
            return false;
        }
        if (batchList.isEmpty()) {
            info("请先选择商品批次");
            return false;
        }
        String commodityAmount = etCommodityAmount.getText().toString().trim();
        if (TextUtils.isEmpty(commodityAmount)) {
            info("上架数量为必填项");
            return false;
        }
        if (!NumberUtils.isInt(commodityAmount) || NumberUtils.getIntegerValue(commodityAmount) <= 0) {
            info("上架数量必须为整数且必须大于0");
            return false;
        }

        if (NumberUtils.getIntegerValue(commodityAmount) > (NumberUtils.getIntegerValue(tvOrderCommodityAmount.getText()) - NumberUtils.getIntegerValue(tvCommodityShelfAmount.getText()))) {
            info("上架数量必须小于可上架数量");
            return false;
        }

        int commodityType = 1;
        if (btnBad.isChecked()) commodityType = 2;
        commodityEntity.setStockType(commodityType);
        commodityEntity.setPosCode(etShelfPos.getText().toString().trim());
        commodityEntity.setAmount(NumberUtils.getIntegerValue(commodityAmount));
        commodityEntity.setProductionDate(batchList.get(0).getProductionDate());
        commodityEntity.setExpirationDate(batchList.get(0).getExpirationDate());
        commodityEntity.setInDate(batchList.get(0).getInDate());
        commodityEntity.setProductBatchID(batchList.get(0).getProductBatchID());
        //todo 多选批次情况下，此处不可直接set List,点击下一个，348行清除，会导致数据重复
//        commodityEntity.setProductBatchList(batchList);
        return true;
    }

    @Override
    public void onSuccess(Message message) {
        switch (message.what) {
            case InShelfPresenter.IN_CHECK_COMMODITY_CODE:
                commodityEntity = (InCommodityEntity) message.obj;
                tvCommodityName.setText(commodityEntity.getCommodityName());
                tvCommodityCode.setText(commodityEntity.getBarCode());
                tvRecommendPos.setText(commodityEntity.getPosCode());
                int commodityType = 1;
                if (btnBad.isChecked()) commodityType = 2;
                commodityEntity.setStockType(commodityType);
                etShelfPos.requestFocus();
                break;
            case InShelfPresenter.IN_BATCH_SINGLE_SUBMIT:
                success("上架提交成功!");
                resetView(true);
                break;
            case InShelfPresenter.CHECK_COMPLETE:
                new TaskCompleteDialog(getActivity()).show();
                break;
        }
    }

    @Override
    protected boolean isUseEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onEventCome(Event event) {
        if (event == null) {
            return;
        }
        switch (event.getCode()) {
            case EventConfig.SHELF_SELECT_BATCH:
                batchList.clear();
                ShelfBatchEntity batchEntity = (ShelfBatchEntity) event.getData();
                batchList.add(batchEntity);
                mAdapter.notifyDataSetChanged();
                int sumPlan = 0;
                int sumUp = 0;
                for (int i = 0; i < batchList.size(); i++) {
                    sumPlan += batchList.get(i).getPlanAmount();
                    sumUp += batchList.get(i).getUpAmount();
                }
                tvOrderCommodityAmount.setText(sumPlan + "");
                tvCommodityShelfAmount.setText(sumUp + "");
                success("批次选择成功！");
                break;
        }
    }


    @OnClick({R.id.btn_good, R.id.btn_bad, R.id.btn_submit, R.id.btn_next, R.id.ll_select_batch, R.id.iv_toggle_batch})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_good:
                btnGood.setChecked(true);
                btnBad.setChecked(false);
                break;
            case R.id.btn_bad:
                btnGood.setChecked(false);
                btnBad.setChecked(true);
                break;
            case R.id.ll_select_batch:
                if (commodityEntity != null) {
                    SelectBatchActivity.start(getContext(), inOrder, commodityEntity, true);
                } else {
                    info("请先扫描商品");
                }
                break;
            case R.id.iv_toggle_batch:
                expandLayout.toggle(true);
                break;
            case R.id.btn_submit:
                if (verifySubmit()) {
                    if (!isAdded)
                        isAdded = inCommodityList.add(commodityEntity);
                    mPresenter.submitSingleAndBatchShelf(
                            taskEntity,
                            inOrder,
                            inCommodityList, beginTime);
                }
                break;
            case R.id.btn_next:
                if (verifySubmit()) {
                    inCommodityList.add(commodityEntity);
                    mPresenter.submitSingleAndBatchShelf(
                            taskEntity,
                            inOrder,
                            inCommodityList, beginTime);
                }
                break;
        }
    }

    /**
     * 重置页面
     *
     * @param isConfirm
     */
    private void resetView(boolean isConfirm) {
        if (isConfirm)
            inCommodityList.clear();
        batchList.clear();
        mAdapter.notifyDataSetChanged();
        expandLayout.collapse();
        commodityEntity = null;
        btnSubmit.setEnabled(false);
        btnNext.setEnabled(false);
        btnGood.setChecked(true);
        btnBad.setChecked(false);
        tvCommodityCode.setText("");
        tvCommodityName.setText("");
        etCommodityAmount.setText("");
        etShelfPos.setText("");
        tvOrderCommodityAmount.setText("");
        tvCommodityShelfAmount.setText("");
        nestedScrollView.smoothScrollTo(0, 0);
        scanText.requestFocus();

        mPresenter.loadInCommodityList(inOrder != null ? String.valueOf(inOrder.getInID()) :  taskEntity.getMainBillID() + "", false);
    }

    @Override
    public <R> LifecycleTransformer<R> toLifecycle() {
        return bindToLifecycle();
    }

    public static BaseViewPagerFragment newInstance(Bundle bundle) {
        ShelfBatchFragment fragment = new ShelfBatchFragment();
        fragment.setArguments(bundle);
        return fragment;
    }
}
